package cn.edu.nwpu.warehousemanagement.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Date;
import java.util.Map;

/**
 * Jwt工具类
 * 生成token和解析token
 * Hutool也提供了JWT工具类
 *
 * @author Loadstar
 * @version 1.0
 */
@Component
public class JwtUtil {
    private static String KEY;
    private static long EXPIREHOUR;
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expireHour}")
    private int expireHour;

    /**
     * 接收业务数据,生成token并返回
     */
    public static String getToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + Duration.ofHours(EXPIREHOUR).toMillis()))   //过期时间，毫秒换算为小时，共3小时
                .sign(Algorithm.HMAC256(KEY));  //加密算法
    }

    /**
     * 接收token,验证token,并返回业务数据
     */
    public static Map<String, Object> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(KEY))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
    }

    @PostConstruct
    public void init() {
        KEY = secret;
        EXPIREHOUR = expireHour;
    }

}